package cemp.service;

import cemp.common.http.stockapi.response.HttpStockApiDataResponse;
import cemp.common.http.stockapi.response.HttpStockApiIsTradeResponse;
import cemp.common.util.DateUtil;
import cemp.entity.StockAll;
import cemp.mapper.StockAllMapper;
import cemp.mapper.StockAvgMapper;
import cemp.redis.constant.RedisKey;
import cemp.redis.util.RedisUtils;
import cemp.util.StockHttpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

import static cemp.common.constant.StockCommonConstant.*;

@Service
@RequiredArgsConstructor
@Slf4j
public class StockCommonUtil {

    private final StockAvgMapper stockAvgMapper;
    private final StockAllMapper stockAllMapper;
    private final RestTemplate restTemplate;
    private final RedisUtils redisUtils;

    public List<StockAll> queryAllStocks(){
        return stockAllMapper.selectList(null);
    }

    public boolean isOpen(String date){
        boolean isOpen = true;
        try {
            LocalDate ldate = DateUtil.str2LocalDate(date);
            //先查询redis中有没有
            Object isOpenObj =  redisUtils.hget(RedisKey.STOCK_ISOPEN.concat(String.valueOf(ldate.getYear())),date);
            if(isOpenObj == null){

                //判断是否周末
                if(DateUtil.str2LocalDate(date).getDayOfWeek().getValue() > 5 ){
                    isOpen = false;
                }else{
                    String url = String.format("%s%s?token=%s&tradeDate=%s",STOCK_HOST,STOCK_IS_TRADEDAY,STOCK_TOKEN,date);
                    //调用api
                    ResponseEntity<HttpStockApiDataResponse<HttpStockApiIsTradeResponse>> response = StockHttpUtil.doGet(restTemplate,
                            url,
                            HttpMethod.GET,
                            new ParameterizedTypeReference<HttpStockApiDataResponse<HttpStockApiIsTradeResponse>>() {}
                    );
                    if(response != null){
                        if(((HttpStockApiIsTradeResponse)response.getBody().getData()).getIsTradeDate() == 0){
                            isOpen=  false;
                        }
                    }
                }
                redisUtils.hset(RedisKey.STOCK_ISOPEN.concat(String.valueOf(ldate.getYear())),date,isOpen);
            }else {
                isOpen =  (Boolean) isOpenObj;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }

        return isOpen;
    }


}
